console.log("loading: template.manager.js");
var Templates = {};
var TemplateUsedWebStorage = false;

function TM_IsCached(templatename) {
	return (Templates[templatename] != undefined);
};

function TM_IsLoading(templatename) {
	return (Templates[templatename] != undefined)
			&& (Templates[templatename].isLoading == true);
};

function TM_GetTemplates(params, onallload) {
	if (params == undefined) {
		return;
	}
	var count = 0;
	var paramQ = {};
	for ( var i in params) {
		var item = params[i];

		// Web storage
		var notFound = Templates[i] == undefined;
		if (notFound && TemplateUsedWebStorage && window.sessionStorage!=undefined){
			var tmp = window.sessionStorage[Config.Profile.Locale+"_*_"+i];
			if (tmp != undefined){
				try{
					Templates[i] = eval(tmp);
					notFound = false;
				}catch(ee){
					console.error(ee);
				}
			}
		}
		
		if (notFound) {
			paramQ["control_id_" + count] = i;
			count++;
			var tmp = {
				isLoading : true
			};
			if (item.onload) {
				tmp.onLoadCallbacks = [ item.onload ];
			}
			Templates[i] = tmp;
		} else {
			delete params[i];
			TM_BindLoadCallback(i, item.onload);
		}
	}
	if (count == 0) {
		if (onallload) {
			onallload();
		}
		return;
	}
	paramQ.control_count = count;
	function loadTemplatesIntoCache(json) {
		if (Error.isError(json)) {
			console.error(Error.getErrorMessages(json));
		}
		for ( var i in params) {
			var template = json[i];
			if (template == undefined) {
				console.error("'" + i + "' - Template not found");
			}
			template.isLoading = false;
			var tmp = Templates[i];
			Templates[i] = template;
			
			// Web storage
			if (window.sessionStorage!=undefined){
				window.sessionStorage[Config.Profile.Locale+"_*_"+i] = "( "+$.toJSON(template)+" )";
			}
			
			TM_ExecLoadCallback(tmp.onLoadCallbacks, template);
		}
		if (onallload) {
			onallload();
		}
	}
	$.post(Handlers.templateManager, paramQ, loadTemplatesIntoCache, "json");
	/*
	 * console.log("post:url:'" + Handlers.templateManager + "'\ndata:\n" +
	 * $.toJSON(paramQ));
	 */

	// Enabled cache
	/*
	 * $.ajax({ type: "POST", url:Handlers.templateManager, data:paramQ,
	 * cache:true, dataType:"json" success:loadTemplatesIntoCache });
	 */
};

function TM_ExecLoadCallback(callbacks, params) {
	if (callbacks == undefined) {
		return false;
	}
	for ( var i = callbacks.length; i > 0; i--) {
		callbacks[i - 1](params);
	}
};

function TM_BindLoadCallback(templatename, onload) {
	if (onload == undefined) {
		return;
	}
	var tmp = Templates[templatename];
	if (tmp == undefined) {
		console.error("Template '" + templatename + "' not loading");
		return false;
	} else if (tmp.isLoading == false) {
		onload(tmp);
	} else {
		if (tmp.onLoadCallbacks == undefined) {
			tmp.onLoadCallbacks = [ onload ];
		} else {
			tmp.onLoadCallbacks.push(onload);
		}
	}
	return true;
};

function TM_GetTemplate(templatename, onload) {
	
	// Web storage
	var notFound = Templates[templatename] == undefined;
	if (notFound &&  TemplateUsedWebStorage && window.sessionStorage!=undefined){
		var tmp = window.sessionStorage[Config.Profile.Locale+"_*_"+templatename];
		if (tmp != undefined){
			try{
			Templates[templatename] = eval(tmp);
			notFound = false;
			}catch(ee){
				console.error(ee);
			}
		}
	}
	
	if (notFound) {
		var tmp = {
			isLoading : true
		};
		if (onload) {
			tmp.onLoadCallbacks = [ onload ];
		}
		Templates[templatename] = tmp;
		function loadTemplateIntoCache(template) {
			if (Error.isError(template)) {
				console.error(Error.getErrorMessages(template));
			}
			template.isLoading = false;
			Templates[templatename] = template;
			
			// Web storage
			if (window.sessionStorage!=undefined){
				window.sessionStorage[Config.Profile.Locale+"_*_"+templatename] = "( "+$.toJSON(template)+" )";
			}
			
			TM_ExecLoadCallback(tmp.onLoadCallbacks, template);
		}
		$.getJSON(Handlers.templateManager + "?control=" + templatename,
				loadTemplateIntoCache);
		/*console.log("get:url:'" + Handlers.templateManager + "?control="
				+ templatename + "'");*/
		// Enabled cache
		/*
		 * $.ajax({ type: "GET",
		 * url:Handlers.templateManager+"?control="+templatename, cache:true,
		 * dataType:"json", success:loadTemplateIntoCache });
		 */
	} else {
		TM_BindLoadCallback(templatename, onload);
	}
};

function TM_GetTemplateFromCache(templatename) {
	return Templates[templatename];
};

function TM_GetTemplateRawFromCache(templatename) {
	return Templates[templatename].raw.join('');
};

function TM_GetFlatTemplateData(data) {
	if (data == undefined) {
		return "undefined";
	}
	var tmp = "";
	for ( var i in data) {
		if (data[i] != undefined && typeof (data[i]) == 'object') {
			tmp += i + "(" + TM_GetFlatTemplateData(data[i]) + ")";
		} else {
			tmp += i + "|";
		}
	}
	return tmp;
}

function TM_FillTemplateData(templatename, data) {
	var template = Templates[templatename];
	if (template == undefined) {
		console.error("Template '" + templatename + "' not found in cachce");
		return;
	} else {
		if (template.isLoading == true) {
			console.error("Template '" + templatename + "' is loading");
			return;
		}
	}
	// template={locale:locale,params:parameters,raw}
	var params = template.params;
	var raw = template.raw;
	for ( var i in params) {
		var cpath = data;
		if (i == '_T-P_') {
			cpath = TM_GetFlatTemplateData(data);
		} else {
			var paths = i.split(/\./g);
			for ( var ii = 0; ii < paths.length; ii++) {
				if (cpath == undefined) {
					break;
				} else {
					cpath = cpath[paths[ii]];
				}
			}
			if (cpath == undefined) {
				cpath = "";
			}
		}

		var paramList = params[i];
		for ( var ii = 0; ii < paramList.length; ii++) {
			raw[paramList[ii]] = cpath;
		}
	}
	return raw.join('');
};